package com.lhdx.practical.service.impl;

import com.lhdx.practical.bean.Depart;
import com.lhdx.practical.dao.DepartDao;
import com.lhdx.practical.service.DepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("DepartService")
public class DepartServiceImpl implements DepartService {
    @Autowired
    private DepartDao departDao;

    @Override
    public Depart findById(long id) {
        return departDao.findById(id);
    }

    @Override
    public void save(Depart depart) {
        departDao.save(depart);
    }

    @Override
    public List<Depart> getAllDepart() {
        return null;
    }

    @Override
    public List<Depart> findAllByPid(long pid) {
        return departDao.findAllByPidOrderBySortDesc(pid);
    }

    @Override
    public List<Depart> findAllByPidNotOrderBySortDesc(long pid) {
        return departDao.findAllByPidNotOrderBySortDesc(pid);
    }

    @Override
    public void deleteById(long id) {
        departDao.deleteById(id);
    }

    @Override
    public int countAllByPid(long pid) {
        return departDao.countAllByPid(pid);
    }

    @Override
    public int countAllByDepartname(String departname) {
        return departDao.countAllByDepartname(departname);
    }

    @Override
    public Page<Depart> getResultList(int page, int pagesize) {
        List<Sort.Order> orders=new ArrayList<>();
        orders.add( new Sort.Order(Sort.Direction. ASC, "pid"));
        orders.add( new Sort.Order(Sort.Direction. DESC, "sort"));
        Pageable pageable = PageRequest.of(page == 0 ? 0 : page -1, pagesize, new Sort(orders));
        Page<Depart> data = departDao.findAll(new Specification<Depart>(){
            @Override
            public Predicate toPredicate(Root<Depart> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.notEqual(root.get("pid"),0));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageable);
        return data;
    }
}
